package com.flyan.game.motafx.component.item;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import com.almasb.fxgl.core.util.LazyValue;
import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.Entity;
import com.almasb.fxgl.entity.component.Component;
import com.almasb.fxgl.physics.BoundingShape;
import com.almasb.fxgl.physics.HitBox;
import com.almasb.fxgl.texture.AnimatedTexture;
import com.flyan.game.motafx.config.GameConfig;
import com.flyan.game.motafx.core.enums.EntityTypeEnum;
import com.flyan.game.motafx.core.util.animate.StillAnimateTable;
import com.flyan.game.motafx.core.util.entity.EntityUtils;
import com.flyan.game.motafx.core.util.sound.SoundUtils;
import com.flyan.game.motafx.effect.BaseEffect;
import com.flyan.game.motafx.entity.item.ItemEntityInfo;

/**
 * 物品组件
 *
 * @author flyan
 * @version 1.0
 * @email flyan_by_chenu@sina.com
 * @since 2025/2/1
 */
public class ItemComponent extends Component {

    private AnimatedTexture atView;

    /**
     * 物品动画
     */
    private LazyValue<StillAnimateTable> animateTable = new LazyValue<>(() -> new StillAnimateTable(
            FXGL.image("materials/items.png"), GameConfig.GRID_SIZE, GameConfig.GRID_SIZE));

    public ItemComponent() {

    }

    @Override
    public void onAdded() {
        EntityTypeEnum type = (EntityTypeEnum) entity.getType();
        atView = new AnimatedTexture(animateTable.get().get(type.getType()));

        /* 挂载并播放动画 */
        entity.getViewComponent().addChild(atView);
        entity.getBoundingBoxComponent().addHitBox(new HitBox(BoundingShape.box(
                GameConfig.GRID_BBOX_SIZE,
                GameConfig.GRID_BBOX_SIZE)));
        entity.setEverUpdated(true);
        atView.loop();
    }

    /**
     * 碰撞开始
     *
     * @param other 碰到到物品的其他实体
     */
    public void onCollisionBegin(Entity other) {
        /* 角色可以和物品交互 */
        if (other.getType() == EntityTypeEnum.CHARACTER_BRAVE) {
            ItemEntityInfo itemInfo = EntityUtils.getEntityInfo(entity, ItemEntityInfo.class);
            /* 触发物品效果 */
            if (CollUtil.isNotEmpty(itemInfo.getEffects())) {
                itemInfo.getEffects().forEach(it -> {
                    BaseEffect effect = ReflectUtil.newInstance(it);
                    effect.setTriggerEntity(entity);
                    effect.apply(other);
                });
            }
            /* 捡起后物品消失 */
            SoundUtils.play("item.wav");
            entity.removeFromWorld();
        }
    }

}
